'''
Manage time drift
'''

SCHEMA_DRIFT = '''CREATE TABLE IF NOT EXISTS time_drift (
    `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `duration_ms` BIGINT UNSIGNED,
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `applied_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)
'''


def schema_drift(conn):
    '''
    Create schema for table time_drift.
    '''
    with conn.cursor() as cur:
        cur.execute(SCHEMA_DRIFT)


def get_drift(conn):
    '''
    Query time drift from database connection

    The last applied dirft will be used.
    '''
    # Synchronize with database, in case drift is inserted while running.
    conn.commit()

    drift = None
    with conn.cursor() as cur:
        count = cur.execute('SELECT duration_ms FROM time_drift'
                            ' WHERE applied_at <= CURRENT_TIMESTAMP()'
                            ' ORDER BY applied_at DESC LIMIT 1')
        if count == 1:
            drift = cur.fetchone()[0]
    return drift
